package com.yusp75.myexam.ad

import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdValue
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.RequestConfiguration
import com.google.android.gms.ads.appopen.AppOpenAd
import com.google.android.gms.ads.appopen.AppOpenAd.AppOpenAdLoadCallback
import java.util.Date


class OpenAdManager(private val context: Context) {
    companion object {
        //private const val AD_UNIT_ID = "ca-app-pub-3940256099942544/9257395921"
        private const val AD_UNIT_ID = "ca-app-pub-3651532828568448/4366146990"
    }

    private var appOpenAd: AppOpenAd? = null
    private var isLoadingAd = false
    private var loadTime: Long = 0
    private val adExpirationMillis = 4 * 60 * 60 * 1000 // 4小时有效期

    fun loadAd() {
        if (isLoadingAd || isAdAvailable()) return

        isLoadingAd = true
        val requestConfig = RequestConfiguration.Builder()
            //.setTestDeviceIds(listOf("33BE2250B43518CCDA7DE426D04EE231"))
            .build()
        MobileAds.setRequestConfiguration(requestConfig)
        val adRequest = AdRequest.Builder().build()

        AppOpenAd.load(
            context,
            AD_UNIT_ID,
            adRequest,
            object : AppOpenAdLoadCallback() {
                override fun onAdLoaded(ad: AppOpenAd) {
                    appOpenAd = ad
                    isLoadingAd = false
                    loadTime = Date().time
                    ad.setOnPaidEventListener { adValue ->
                        logAdValue(adValue)
                    }
                }

                override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                    isLoadingAd = false
                    Handler(Looper.getMainLooper()).postDelayed({
                        loadAd()
                    }, 5000)
                }
            }
        )
    }

    // 接口定义
    interface OnShowAdCompleteListener {
        fun onShowAdComplete()
    }

    fun showAdIfAvailable(activity: Activity, listener: OnShowAdCompleteListener) {
        if (isAdAvailable()) {
            appOpenAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdDismissedFullScreenContent() {
                    cleanupAdResources()
                    listener.onShowAdComplete()
                }

                override fun onAdFailedToShowFullScreenContent(adError: AdError) {
                    cleanupAdResources()
                    listener.onShowAdComplete()
                }

                private fun cleanupAdResources() {
                    appOpenAd?.fullScreenContentCallback = null
                    appOpenAd = null
                    loadAd() // 异步加载下个广告
                }
            }
            appOpenAd?.show(activity)
        } else {
            listener.onShowAdComplete()
            loadAd() // 异步加载广告
        }
    }

    private fun isAdAvailable(): Boolean {
        return appOpenAd != null &&
                (Date().time - loadTime) < adExpirationMillis
    }

    private fun logAdValue(adValue: AdValue) {
        // 广告收益分析实现
    }

    fun preloadAd() {
        val adRequest = AdRequest.Builder().build()
        AppOpenAd.load(
            context, AD_UNIT_ID,
            adRequest,
            object : AppOpenAdLoadCallback() {
                override fun onAdLoaded(ad: AppOpenAd) {
                    appOpenAd = ad
                }

                override fun onAdFailedToLoad(error: LoadAdError) {
                    Log.e("AdError", error.message)
                }
            })
    }

}
